import React,{useState,useEffect} from 'react';
import './App.css';
import "bootstrap/dist/css/bootstrap.min.css"
import FileSearch from "./components/FileSearch.js"
import FileList from "./components/FileList.js"
import defaultFiles from "./utils/defaultFiles.js"
//import localhost file action
import fileHelper from "./utils/fileHelper.js"
//暂时不使用这种方式
import {flattenArr,objToArr} from "./utils/helper.js"

import BottomBtn from './components/BottomBtn.js'
import TabList from "./components/TabList.js"

//引入react-simplemde-editor 是 easymde 的react版本
import SimpleMDE from "react-simplemde-editor";
import "easymde/dist/easymde.min.css";
//import uuid/v4
import { v4 as uuidv4 } from 'uuid';

import { faPlus,faFileImport } from '@fortawesome/free-solid-svg-icons'
//require nodejs
const path = window.require('path')
const {remote,ipcRenderer} = window.require("electron")
const Store = window.require("electron-store");
const settingsStore = new Store({name: 'Settings'});//设置配置
const fileStore = new Store({"name":"Files Data"});//生成的josn文件名称为FIles Data.json


const saveFilesStore = (files)=>{
  //save some info in file sysytem
  const filesStoreObj = files.reduce((result,file)=>{
     const { id,path,title,createdAt} = file;
     result[id] = {
       id,
       path,
       title,
       createdAt
     }
     return result
  },{})
  fileStore.set({'files':filesStoreObj})
}

function App() {
  // const [files,setFiles] = useState(defaultFiles);
  //对象转数组
  const defaultFiles = fileStore.get('files');
  const defaultFilesArr = defaultFiles ? objToArr(defaultFiles) : []

  const [files,setFiles] = useState(defaultFilesArr);
  const [openFileIds,setOpenFileIds] = useState([]);
  const [activeFileId, setActiveFileId] = useState("");//激活正在编辑的文件id
  const [unSaveFileIds,setUnSaveFileIds] = useState([]);//待保存的文件id数组
  const [searchFiles,setSearchFiles] = useState(false);//保存搜索的结果
  //文件保存路劲
  const saveLocationPath =  settingsStore.get('savedFileLocation') || remote.app.getPath("documents")

  const openFiles = openFileIds.map(openid=>{
    return files.find(file=>file.id ===openid)
  })
  // current openfile
  const activeFile = files.find(file=>file.id===activeFileId);

  //click file to look file's content
  const fileClick=(id)=>{
    const currentFile = files.find(file => file.id===id)
    //no read file's content once
    if(!currentFile.isLoaded){
        fileHelper.readFile(currentFile.path).then((res)=>{
          const newFiles = files.map((file)=>{
             if(file.id == id){
               file.isLoaded = true
               file.body = res
             }
             return file
          });
          setFiles(newFiles)
          //set current active file
          setActiveFileId(id);
          //if openFileIds don't have current id
          //then add id to openFileIds
          if(!openFileIds.includes(id)){
            setOpenFileIds([...openFileIds,id])
          }
        }).catch((rej)=>{//When the file does not exist
          console.log("文件不存在了")
          const newFiles = files.filter(file=>file.id != id)
          setFiles(newFiles)
          saveFilesStore(newFiles)
        })
    }else{
        //set current active file
        setActiveFileId(id);
        //if openFileIds don't have current id
        //then add id to openFileIds
        if(!openFileIds.includes(id)){
          setOpenFileIds([...openFileIds,id])
        }
    }
  }

  const tabChooseFn = (id)=>{
    //set activeFileid
     setActiveFileId(id)
  }
  const tabCloseFn = (id)=>{
    //close tab
    const noclose = openFileIds.filter(openID=>openID != id);
    setOpenFileIds(noclose)
    if(noclose.length > 0){
       setActiveFileId(noclose[0])
    }else{
       setActiveFileId("")
    }
  }


  //save file's content to md
  const saveContentToMd = ()=>{
     if(activeFile){
       fileHelper.writeFile(activeFile.path,activeFile.body).then((res)=>{
         const newUnSaveFilesIds= unSaveFileIds.filter(id => id !== activeFile.id)
         setUnSaveFileIds(newUnSaveFilesIds)
       })
     }
  }
  const changeFileFn = (id,value)=>{
    //没有改变不进行变化
    const modifyFile = files.find(file=>file.id ===id)
    if(modifyFile.body == value){
       return;
    }

    //modify file's body
     const modifyFileArr = files.map(file=>{
        if(file.id === id){
           file.body = value;
        }
        return file
     })
     setFiles(modifyFileArr)
     //set unSaveFileIds
     if(!unSaveFileIds.includes(id)){
       setUnSaveFileIds([...unSaveFileIds,id])
     }
  }

  //delete files
  const delFileFn = (id)=>{
      const delFile = files.find(file=>file.id === id);
      const newFiles = files.filter(file=>file.id !== id);
      if(delFile && delFile.path){
          fileHelper.deleteFile(delFile.path).then(()=>{
            setFiles(newFiles)
            saveFilesStore(newFiles);
            //close the tab if opened
            tabCloseFn(id)
          }).catch((rej)=>{
            console.log("删除失败")
            console.log(rej)
          })
      }else if(delFile){
          setFiles(newFiles)
          saveFilesStore(newFiles);
          //close the tab if opened
          tabCloseFn(id)
      }
  }
  //change file's name
  const changeFileNameFn = (id, title,isnew)=>{
     let tempBody = "";
     let tempTitle = "";
     let tempPath = ""
     const changeFileInfo = files.find((file)=>{
       if(file.id === id){
         tempTitle = file.title;
         tempBody = file.body;
         tempPath = file.path;
         return file
       }
     })
     const newpath = isnew ? path.join(saveLocationPath,`${title}.md`) : path.join(path.dirname(tempPath),`${title}.md`)
     // console.log(fileHelper.hasFile(newpath))
     //file不存在
     fileHelper.hasFile(newpath).then((res)=>{
       console.log("文件存在")
       //find need changed file
     }).catch((rej)=>{
         console.log("文件不存在")
         const oldpath = tempPath;
         const modifiedFile = { ...changeFileInfo,title,path:newpath,isNew:false }
         const otherFiles = files.filter((file)=>{
           if(file.id != id){
             return file
           }
         })
         const newFiles = [...otherFiles,modifiedFile]
         // new file
         if(isnew){
            fileHelper.writeFile(newpath,tempBody).then(()=>{
              setFiles(newFiles);
              saveFilesStore(newFiles)
            })
         }else{
             fileHelper.renameFile(oldpath,newpath).then(()=>{
               setFiles(newFiles)
               saveFilesStore(newFiles)
             })
         }
     })
  }

  //search file
  const searchFileFn = (keyword)=>{
     const searchFile = files.filter(file=>{
        if(file.title.includes(keyword)){
           return file;
        }
     })
     // console.log(searchFile);/触发多次
     setSearchFiles(searchFile)
     // setFiles(searchFile)
  }

  //create new files
  const createNewFile = ()=>{
     const newId = uuidv4();
     const newFiles = [
       ...files,
       {
         id:newId,
         title:"",
         body:"## 请输入 MARKDOWN",
         createdAt:new Date().getTime(),
         isNew:true,
       }
     ];
     setFiles(newFiles)
  }

  //import file
  const importFileFn = ()=>{
    //open file choose dialog
    remote.dialog.showOpenDialog({
        title:"选择Markdown文件",
        properties:["openFile","multiSelections"],
        filters:[
          {name:"MarkDown",extensions:['md']}
        ]
    }).then(res=>{
        if(!res.canceled){
           //去重
           const pathArr =  res.filePaths.filter(pathone=>{
              if(!files.find(file=>file.path === pathone)){
                return pathone
              }
           })
           const filterFileArr = pathArr.map(pathone=>{
               const statinfo = fileHelper.statSyncFile(pathone)
               return {
                 id:uuidv4(),
                 path:pathone,
                 title:path.basename(pathone,".md"),
                 createdAt:(new Date(statinfo.birthtime)).getTime()
               }
           });
           setFiles([...files,...filterFileArr])
           saveFilesStore([...files,...filterFileArr])

           if(pathArr.length > 0){
              remote.dialog.showMessageBox({
                type:"info",
                title:"导入成功",
                message:`成功导入了${pathArr.length}份文件`
              })
           }
        }
    }).catch(rej=>{
        console.log(rej)
    })
  }

  //监听webContents.send
  useEffect(()=>{
     const newFileCallback =()=>{
        createNewFile()
     }
     const importFileCallback =()=>{
        importFileFn()
     }
     const saveFileCallback =()=>{
        saveContentToMd()
     }
     ipcRenderer.on("create-new-file",newFileCallback)
     ipcRenderer.on("import-file",importFileCallback)
     ipcRenderer.on("save-edit-file",saveFileCallback)

     return ()=>{
        ipcRenderer.removeListener("create-new-file",newFileCallback)
        ipcRenderer.removeListener("import-file",importFileCallback)
        ipcRenderer.removeListener("save-edit-file",saveFileCallback)

     }
  })
  const filesListArr = (searchFiles || searchFiles.length > 0) ? searchFiles : files;
  return (
    <div className="App container-fluid px-0">
        <div className="row no-gutters">
            <div  className="col-3 left-panel">
              <FileSearch onFileSearch={searchFileFn} />
              <FileList files={filesListArr} onFileClick={fileClick} onFileDel={delFileFn}
                onSaveEdit={changeFileNameFn}
              />
            <div className="row no-gutters button_group">
                  <div className="col">
                      <BottomBtn
                          text="新建"
                          colorClass="btn-primary"
                          onBtnClick={createNewFile}
                          icon={faPlus} />
                  </div>
                  <div className="col">
                      <BottomBtn
                          text="导入"
                          colorClass="btn-success"
                          onBtnClick={importFileFn}
                          icon={faFileImport} />
                  </div>
              </div>
            </div>
            <div  className="col-9 right-panel">
              { !activeFile &&
                <div className="no_file_open">
                  选择或者新建 MarkDown文档
                </div>
              }
              { activeFile &&
                <>
                  <TabList files={openFiles}
                   onChooseId={activeFileId}
                   noSaveArr={unSaveFileIds}
                   onCloseFn={tabCloseFn}
                   onChooseFn={tabChooseFn}
                  />
                  <SimpleMDE
                  key={activeFile && activeFile.id}
                  value={activeFile && activeFile.body}
                  onChange={(value)=>{changeFileFn(activeFile.id,value)}}
                  options={{
                    minHeight:"454px"
                  }}/>
                </>
              }
            </div>
        </div>
    </div>
  );
}

export default App;
